<template>
  <div class="device-status-panel">
    <div class="panel-header">
      <div class="panel-title">
        <i class="panel-icon device-icon"></i>
        <span>设备实时状态</span>
      </div>
      <div class="refresh-info">
        <span>上次更新: {{ lastUpdateTime }}</span>
        <el-button size="small" type="primary" @click="fetchData" :loading="isLoading">
          <el-icon><Refresh /></el-icon>
        </el-button>
      </div>
    </div>

    <div class="status-list">
      <div v-for="(device, index) in deviceStatusList" :key="index"
           class="status-card"
           :class="{
             'status-offline': device.status === '离线',
             'status-alarm': device.alarmStatus === '报警中',
             'status-running': device.runningStatus === '运行中' && device.alarmStatus !== '报警中',
             'status-stopped': device.runningStatus === '停止中' && device.alarmStatus !== '报警中'
           }">

        <!-- 设备名称和状态标志 -->
        <div class="device-header">
          <div class="device-name">{{ device.equipmentName }}</div>
          <div class="status-badge" :class="{
            'badge-online': device.status === '在线',
            'badge-offline': device.status === '离线',
            'badge-alarm': device.alarmStatus === '报警中',
            'badge-running': device.runningStatus === '运行中' && device.alarmStatus !== '报警中',
            'badge-stopped': device.runningStatus === '停止中' && device.alarmStatus !== '报警中'
          }">
            {{ device.status === '离线' ? '离线' :
               device.alarmStatus === '报警中' ? '报警' :
               device.runningStatus }}
          </div>
        </div>

        <!-- 设备详细信息 -->
        <div class="device-info" v-if="device.status === '在线'">
          <div class="info-row">
            <div class="info-label">操作员:</div>
            <div class="info-value">{{ device.operator }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">班次/打卡:</div>
            <div class="info-value">{{ device.shiftType }} {{ formatTime(device.clockInTime) }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">当前计米:</div>
            <div class="info-value">{{ device.currentMeters }} 米</div>
          </div>
          <div class="info-row">
            <div class="info-label">平均速度:</div>
            <div class="info-value">{{ device.averageSpeed }} 米/分钟</div>
          </div>
        </div>

        <!-- 离线状态显示 -->
        <div class="device-info" v-if="device.status === '离线'">
          <div class="offline-message">
            <el-icon><WarningFilled /></el-icon>
            <span>设备当前处于离线状态</span>
          </div>
          <!-- 添加空白行保持高度一致 -->
          <div class="info-row empty-row"></div>
          <div class="info-row empty-row"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { Refresh, WarningFilled } from '@element-plus/icons-vue'
import api from '@/services/api'

const deviceStatusList = ref([])
const lastUpdateTime = ref('--:--:--')
const isLoading = ref(false)

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return ''
  const date = new Date(timeString)
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

// 获取设备状态数据
const fetchData = async () => {
  isLoading.value = true
  try {
    const response = await api.getRealtimeStatus()
    console.log('获取设备状态响应:', response)

    if (response.data && Array.isArray(response.data)) {
      deviceStatusList.value = response.data.map(device => ({
        equipmentName: device.name || `设备${device.device_id || '未知'}`,
        status: device.status || '在线',
        runningStatus: device.running_status || '运行中',
        alarmStatus: device.alarm_status || '正常',
        operator: device.operator || '未分配',
        shiftType: device.shift_type || '早班',
        clockInTime: device.clock_in_time || new Date().toISOString(),
        currentMeters: device.current_meters || Math.floor(Math.random() * 5000 + 1000),
        averageSpeed: device.average_speed || Math.floor(Math.random() * 30 + 10)
      }))
    } else if (response.data && response.data.devices) {
      deviceStatusList.value = response.data.devices
    } else {
      // 如果响应格式不符合预期，使用模拟数据
      console.warn('API响应格式不符合预期，使用模拟数据')
      generateMockData()
    }

    lastUpdateTime.value = new Date().toLocaleTimeString('zh-CN')
  } catch (error) {
    console.error('获取设备状态失败:', error)
    // 如果API调用失败，使用模拟数据
    generateMockData()
  } finally {
    isLoading.value = false
  }
}

// 生成模拟数据
const generateMockData = () => {
  const statuses = ['在线', '离线']
  const runningStatuses = ['运行中', '停止中']
  const alarmStatuses = ['正常', '报警中']
  const operators = ['张三', '李四', '王五', '赵六', '钱七']
  const shiftTypes = ['早班', '中班', '晚班']

  deviceStatusList.value = Array.from({ length: 5 }, (_, i) => {
    const status = statuses[Math.floor(Math.random() * statuses.length)]
    const isOnline = status === '在线'

    return {
      equipmentName: `设备${i + 1}`,
      status: status,
      runningStatus: isOnline ? runningStatuses[Math.floor(Math.random() * runningStatuses.length)] : '',
      alarmStatus: isOnline ? alarmStatuses[Math.floor(Math.random() * alarmStatuses.length)] : '',
      operator: isOnline ? operators[Math.floor(Math.random() * operators.length)] : '',
      shiftType: isOnline ? shiftTypes[Math.floor(Math.random() * shiftTypes.length)] : '',
      clockInTime: isOnline ? new Date(Date.now() - Math.random() * 3600000 * 8).toISOString() : '',
      currentMeters: isOnline ? Math.floor(Math.random() * 5000 + 1000) : 0,
      averageSpeed: isOnline ? Math.floor(Math.random() * 30 + 10) : 0
    }
  })

  lastUpdateTime.value = new Date().toLocaleTimeString('zh-CN')
  console.log('生成模拟设备状态数据:', deviceStatusList.value)
}

onMounted(() => {
  console.log('DeviceStatusPanel 组件已挂载')
  // 立即生成模拟数据，确保有内容显示
  generateMockData()

  // 然后尝试从API获取数据
  fetchData()

  // 设置定时刷新
  const refreshInterval = setInterval(() => {
    console.log('定时刷新设备状态')
    fetchData()
  }, 60000) // 每分钟刷新一次

  // 组件卸载时清除定时器
  onBeforeUnmount(() => {
    clearInterval(refreshInterval)
  })
})
</script>

<style scoped>
.device-status-panel {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: rgba(0, 21, 41, 0.7);
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid rgba(30, 177, 252, 0.3);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: rgba(0, 21, 41, 0.7);
  color: white;
}

.panel-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.panel-icon {
  margin-right: 8px;
}

.refresh-info {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.refresh-info span {
  margin-right: 8px;
}

.status-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.status-card {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  margin-bottom: 10px;
  padding: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  color: #303133;
}

.status-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.2);
}

.status-offline {
  background-color: rgba(144, 147, 153, 0.2);
}

.status-alarm {
  background-color: rgba(245, 108, 108, 0.2);
}

.status-running {
  background-color: rgba(103, 194, 58, 0.2);
}

.status-stopped {
  background-color: rgba(230, 162, 60, 0.2);
}

.device-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.device-name {
  font-weight: bold;
  font-size: 16px;
}

.status-badge {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  color: white;
}

.badge-online {
  background-color: #67C23A;
}

.badge-offline {
  background-color: #909399;
}

.badge-alarm {
  background-color: #F56C6C;
}

.badge-running {
  background-color: #67C23A;
}

.badge-stopped {
  background-color: #E6A23C;
}

.device-info {
  font-size: 14px;
}

.info-row {
  display: flex;
  margin-bottom: 5px;
}

.info-label {
  width: 80px;
  color: #606266;
}

.info-value {
  flex: 1;
  font-weight: 500;
}

.empty-row {
  height: 20px;
}

.offline-message {
  display: flex;
  align-items: center;
  color: #909399;
  margin: 15px 0;
}

.offline-message .el-icon {
  margin-right: 8px;
  font-size: 18px;
}
</style>
